﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Configuration;
using System.Threading;

namespace Quartz.JobClass
{
    public class SocketService
    {
        /// <summary>
        /// 存报文字节数组
        /// </summary>
        private static byte[] result = new byte[8000];
        /// <summary>
        /// 连接对象
        /// </summary>
        private static Socket serverSocket;

        public static void Start()
        {
            try
            {
                IPAddress ip = IPAddress.Parse(ConfigurationManager.AppSettings["FTP_IP"]);//IP地址
                int myProt = Convert.ToInt32(ConfigurationManager.AppSettings["FTP_Port"]);//监听端口 


                serverSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//Socket对象
                serverSocket.Bind(new IPEndPoint(ip, myProt));  //绑定IP地址、端口  
                serverSocket.Listen(30);//设定最多30个排队连接请求  
                LogHelper.Info("(SocketService的Start方法) 监听" + serverSocket.LocalEndPoint.ToString() + "启动");//监听启动 记录日志
                Thread myThread = new Thread(ListenClientConnect);//通过新线程启动新监听
                myThread.Start();//线程开始
            }
            catch (Exception ex)
            {

                LogHelper.Info("启动报错：", ex);
            }
        }

        /// <summary>  
        /// 监听客户端连接  
        /// </summary>  
        private static void ListenClientConnect()
        {
            while (true)//无限循环
            {
                Thread receiveThread = new Thread(ReceiveMessage);//新线程
                receiveThread.Start(serverSocket.Accept());//启动 传入创建的Socket
            }
        }

        /// <summary>  
        /// 接收消息  
        /// </summary>  
        /// <param name="clientSocket"></param>  
        private static void ReceiveMessage(object clientSocket)
        {
            Socket myClientSocket = (Socket)clientSocket;//获得Socket对象
            try
            {
                int receiveNumber = myClientSocket.Receive(result);//接收客户端消息并存入字节数组                    
                #region
                string sByteCount = Convert_Helper.GetGb2312String(result, 0, 6);//帧长度 0到5
                string sSecret = Convert_Helper.GetGb2312String(result, 6, 1);//加密 0：明文；1：表示加密报文 6到6
                LogHelper.Info("(SocketService的ReceiveMessage方法) 接收" + myClientSocket.RemoteEndPoint.ToString() + "报文：" + Convert_Helper.GetGb2312String(result, 0, receiveNumber));//记录接收日志
                if (sSecret == "1")
                {
                    //解密
                }
                string sType = Convert_Helper.GetGb2312String(result, 7, 3);//类型
                string sSendMessage = "";//返回给客户端的消息
                DateTime lastday = DateTime.Now.AddDays(1 - DateTime.Now.Day).AddMonths(1).AddDays(-1);
                DateTime fistday = DateTime.Now.AddDays(1 - DateTime.Now.Day);
                //if (DateTime.Now.Day == lastday.Day)
                //{
                //    if (DateTime.Now >= DateTime.Parse(lastday.ToString("yyyy-MM-dd 21:00:00")))
                //    {
                //        sType = "999";
                //    }
                //}
                //if (DateTime.Now.Day == fistday.Day)
                //{
                //    if (DateTime.Now <= DateTime.Parse(fistday.ToString("yyyy-MM-dd 02:00:00")))
                //    {
                //        sType = "999";
                //    }
                //}
                switch (sType)
                {
                    case "311":
                        sSendMessage = CDE_Engine.getYonghuXXAll(result);//用户信息查询
                        break;
                    case "312":
                        sSendMessage = CDE_Engine.getYonghuXXMod(result);//3.1.2	获取用户变动信息（新增、删除、修改）
                        break;
                    case "313":
                        sSendMessage = CDE_Engine.SelectYonghuXX(result);//3.1.3	获取单个用户信息
                        break;
                    case "321":
                        sSendMessage = CDE_Engine.getHBGXAll(result);//3.2.1	获取全部户表关系
                        break;
                    case "322":
                        sSendMessage = CDE_Engine.getHBGXMod(result);//3.2.2	获取户表关系变动信息（建立、解除）
                        break;
                    case "331":
                        sSendMessage = CDE_Engine.PumpChaoBiaoSJ(result);//3.3	推送抄表数据
                        break;
                    case "332":
                        int NY = Convert.ToInt32(Convert_Helper.GetGb2312String(result, 10, 6));//Char(4)	年
                        sSendMessage = CDE_Engine.PumpChaoBiaoSJALL(NY);//3.3	批量循环推送抄表数据
                        break;
                    case "341":
                        sSendMessage = CDE_Engine.getYuanDingE(result);//3.4.1	获取源定额数据
                        break;
                    case "342":
                        sSendMessage = CDE_Engine.getYuanDingE(result);//3.4.2	获取源定额数据
                        break;
                    case "351":
                        sSendMessage = CDE_Engine.getChaoDingE(result);//3.5.1	获取超定额数据
                        break;
                    case "352":
                        sSendMessage = CDE_Engine.getChaoDingE(result);//3.5.2	获取用户超定额数据
                        break;
                    case "361":
                        sSendMessage = CDE_Engine.PumpKaiZhangSJ(result);//3.6.1	开账数据
                        break;
                    case "362":
                        sSendMessage = CDE_Engine.getKaiZhangError(result);//3.6.2	开账数据
                        break;
                    case "363":
                        sSendMessage = CDE_Engine.PumpKaiZhangSF(result);//3.6.3	收费数据
                        break;


                    case "391":
                        sSendMessage = CDE_Engine.SelectDETZD(result);//定额通知单
                        break;
                    case "392":
                        sSendMessage = CDE_Engine.SelectCDETZD(result);//超定额通知单
                        break;
                    case "393":
                        sSendMessage = CDE_Engine.SelectCDEFHTZD(result);//超定额复核通知单
                        break;



                    case "999":
                        sSendMessage = "19";//999月结
                        LogHelper.Error("(SocketService的ReceiveMessage方法)月结时间段：" + fistday.ToString("yyyy-MM-dd 04:00:00") + "开始" + lastday.ToString("yyyy-MM-dd 21:00:00")+DateTime.Now.ToString());
                        break;
                    default:
                        sSendMessage = "19";//
                        LogHelper.Error("(SocketService的ReceiveMessage方法)未定义的操作");
                        break;

                }
                #endregion
                int iByteLength = Convert_Helper.GetBytes(sSendMessage).Length;
                if (iByteLength <= 8000)
                {
                    //sSendMessage = iByteLength.ToString("D6") + sSecret  + sSendMessage;
                    myClientSocket.Send(Convert_Helper.GetBytes(sSendMessage));
                    LogHelper.Info("(SocketService的ReceiveMessage方法) 返回" + myClientSocket.RemoteEndPoint.ToString() + "报文：" + sSendMessage);
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("(SocketService的ReceiveMessage方法)发生异常：" + ex.Message);
            }
            finally
            {
                myClientSocket.Shutdown(SocketShutdown.Both);//停止监听
                myClientSocket.Close();//关闭本次监听
            }
        }

        public static void Stop()
        {
            try
            {
                //serverSocket.Shutdown(SocketShutdown.Both);//停止监听
                serverSocket.Close();//关闭本次监听
                LogHelper.Info("(SocketService的Start方法) 监听" + serverSocket.LocalEndPoint.ToString() + "关闭");
            }
            catch (Exception ex)
            { 
                LogHelper.Error("(SocketService的Stop方法)发生异常：" + ex.Message);            
            }
        }
    }
}
